package com.alibaba.citrus.ots.platform.enhance.functions.diff.common.dataParser;

import com.alibaba.citrus.ots.platform.enhance.repository.model.diff.common.FieldLineDTO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据转换器
 */
public abstract class DataParser {
    /**
     * 日志
     */
    private Log log = Log.getLogger(DataParser.class);

    /**
     * 解析出字段中的值
     *
     * @return 解析后的字段
     */
    public abstract Map<String, FieldLineDTO> parse(Object obj);

    /**
     * 获取处理类型
     *
     * @return 处理类型
     */
    public abstract String obtainProcessType();

    /**
     * 获取字段映射表
     *
     * @param dataBaseFiledMapping 数据库字段映射成标准字段表
     * @param object               被解析对象
     * @param zClass               解析类的 class文件
     * @return 字段映射
     */
    public Map<String, FieldLineDTO> obtainFieldLineMap(Map<String, String> dataBaseFiledMapping, Object object, Class<?> zClass) {
        Map<String, FieldLineDTO> map = new HashMap<>();
        for (Map.Entry<String, String> entry : dataBaseFiledMapping.entrySet()) {
            Object fieldValue = null;
            try {
                String fieldName = entry.getKey();

                if (StringUtils.contains(fieldName, "features") && StringUtils.contains(fieldName, ".")) {
                    String featuresKey = fieldName.split("\\.")[1];
                    Field featuresField = zClass.getDeclaredField("features");
                    featuresField.setAccessible(true);
                    String featuresValue = (String) featuresField.get(object);
                    fieldValue = JSONObject.parseObject(featuresValue).get(featuresKey);
                }else{
                    Field field = zClass.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    fieldValue = field.get(object);
                }


            } catch (NoSuchFieldException | IllegalAccessException e) {
                log.error("获取字段异常:"+entry.getKey(), e);
            }

            FieldLineDTO fieldLineDTO = null;
            //feature 也会被同步过去
            if (fieldValue != null) {
                fieldLineDTO = FieldLineDTO.of(entry.getKey(), entry.getValue(), fieldValue.toString());
            } else {
                fieldLineDTO = FieldLineDTO.of(entry.getKey(), entry.getValue(), null);
            }
            map.put(entry.getValue(), fieldLineDTO);
        }
        return map;
    }
}
